package controllers

import (
	"fmt"
	"fox/common"
	"fox/enum/auth"
	"fox/enum/code"
	"fox/faker"
	"fox/models"
	"fox/repositories"
	request2 "fox/request"
	"fox/response"
	"fox/validators"
	"github.com/gin-gonic/gin"
	"golang.org/x/crypto/bcrypt"
	"net/http"
	"time"
)

type SysController struct {
	userRepository *repositories.UserRepository
}

func NewSysController() (sysController *SysController) {
	return &SysController{
		userRepository: repositories.NewUserRepository(),
	}
}

func (controller *SysController) Login(c *gin.Context) {
	var (
		loginUser *request2.LoginUser
		user      *models.User
		userToken *models.User
		userGet   *models.User
		userMsg   map[string]interface{}
		err       error
	)

	//获取用户账号密码
	loginUser = &request2.LoginUser{}
	if err = c.ShouldBind(&loginUser); err != nil {
		c.JSON(http.StatusOK, response.Response(code.ParameterError, validators.Translate(err), ""))
		return
	}

	//通过账号查询
	if user, err = controller.userRepository.SelectUserByUsername(loginUser.UserName); err != nil {
		c.JSON(http.StatusOK, response.Response(code.QueryError, err.Error(), ""))
		return
	}
	if user == nil {
		c.JSON(http.StatusOK, response.Response(code.QueryError, "账号不存在", ""))
		return
	}
	//密码比对
	if err = bcrypt.CompareHashAndPassword([]byte(user.Password), []byte(loginUser.Password)); err != nil {
		c.JSON(http.StatusOK, response.Response(code.QueryError, "密码错误", ""))
		return
	}

	//生成token
	userToken = &models.User{}
	userToken.AuthToken = faker.RandString(32)
	userToken.TokenTime = time.Now().Add(time.Duration(auth.Expire) * time.Hour).Format("2006-01-02 15:04:05")
	userToken.ID = user.ID
	userToken.UpdateTime = common.DateTimeNowFormat()
	//保存结果
	if userGet, err = controller.userRepository.UpdateUserById(userToken); err != nil {
		c.JSON(http.StatusOK, response.Response(code.QueryError, "token生成错误", ""))
		return
	}

	userMsg = make(map[string]interface{})
	//struct 转map
	userMsg = common.StructToMap(*userGet)
	if len(userMsg) != 0 {
		userMsg["Password"] = ""
	}
	//返回结果
	c.JSON(http.StatusOK, response.Response(
		200,
		"成功",
		userMsg,
	))
	return
}

func (controller *SysController) Profile(c *gin.Context) {
	var (
		token string
		user  *models.User
		err   error
	)

	token = c.GetHeader(auth.Header)
	fmt.Println("token:", token)
	//header头放到gin.context拿取
	//userC, _ := c.Get("user")
	//转json
	//result, _ := json.Marshal(userC)
	//fmt.Println(string(result))
	//转struct
	//fmt.Println(userC.(*models.User))
	if token == "" {
		c.JSON(http.StatusOK, response.Response(code.ParameterError, "缺少header", ""))
		return
	}

	if user, err = controller.userRepository.SelectUserByToken(token); err != nil {
		c.JSON(http.StatusOK, response.Response(code.QueryError, err.Error(), ""))
		return
	}

	user.Password = ""
	c.JSON(http.StatusOK, response.Response(code.Success, "成功", user))
	return

}
